package com.my.myTradeData.DataSource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.hibernate.Session;

import com.my.myTradeData.DayData;
import com.my.myTradeData.HibernateUtil;
import com.my.myTradeData.JavaFile;
import com.my.myTradeData.VoiceNoteOper;
import com.my.stock.core.KLine;
import com.my.stock.core.Turtle;

public class Sina {
	//
//	https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_symbolsymbolsymboldatedatedate=/InnerFuturesNewService.getDailyKLine?symbol=symbolsymbolsymbol&_=datedatedate
	private static String DATA_SOURCE_URL = "http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesDailyKLine?symbol=";

	private static String DATA_15M_URL = "https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_symbolsymbolsymboldatedatedate=/InnerFuturesNewService.getDailyKLine?symbol=symbolsymbolsymbol&_=datedatedate";

	private static String REALDATA_URL = "http://hq.sinajs.cn/list=";

	public static void get15mData(String code) {

		HttpClient httpclient = new DefaultHttpClient();

		HttpGet httpgets;

		String sinaCode = code;
		if (Character.isUpperCase(code.charAt(0)) && !code.startsWith("IH") && !code.startsWith("IC")
				&& !code.startsWith("IF") && !code.startsWith("IM") && !code.startsWith("T2") && !code.startsWith("TS")
				&& !code.startsWith("TF") && !code.startsWith("TL")) {
			String group = code.replaceAll("\\d+", "");
			sinaCode = code.replaceAll(group, group + "2");
		}

		httpgets = new HttpGet(
				DATA_15M_URL.replaceAll("symbolsymbolsymbol", sinaCode).replaceAll("datedatedate", "2024_11_19"));
		HttpResponse response;
		try {
			response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				String str = convertStreamToString(instreams);
//				System.out.println(str);
				try {
					str = str.substring(2, str.length() - 3);

				} catch (Throwable e) {
					e.printStackTrace();
					System.out.println(code);

				}

				httpgets.abort();

				readDatas(code, str);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return;

	}

	private static String getData(String code) {

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpgets = new HttpGet(REALDATA_URL + code);
		HttpResponse response;
		try {
			response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				String str = convertStreamToString(instreams);
				str = str.substring(2, str.length() - 3);

				httpgets.abort();
				return str;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	public static void getDatas() {
		Set<String> code = Dictionary.SinaDataDictionary.keySet();
		String s = getData("AP0");
		DayData d = readRealtimeDatas("AP0", s);
		Turtle.init(d.getDataDate());
		for (String c : code) {
			Turtle t = Turtle.getInstance(c);
			String returnStr;
			returnStr = getData(c);

			if (returnStr != null && returnStr.length() > 0) {
				DayData dayData = readRealtimeDatas(c, returnStr);
				if (dayData.dataCheck()) {

					DayData dbData = HibernateUtil.selectTodayData(c, dayData.getDataDate());
					Session session = HibernateUtil.getSessionFactory().openSession();
					session.beginTransaction();
					if (dbData == null) {
						session.save(dayData);
					} else {
						dbData.setClose(dayData.getClose());
						dbData.setHigh(dayData.getHigh());
						dbData.setLow(dayData.getLow());
						dbData.setVol(dayData.getVol());
						dbData.setOpen(dayData.getOpen());
						session.update(dbData);

					}
					session.getTransaction().commit();
					if (t.signal(dayData.getClose(), dayData.getClose(), dayData.getClose(), dayData.getClose())) {
						VoiceNoteOper.shortMessageSend();
					}

				} else {
					System.err.println(returnStr + " error");
				}

			}

			// System.out.println(c + " atr:" + getATR(c, 26));
		}
	}

	private static DayData readRealtimeDatas(String code, String str) {
		DayData dd = new DayData();
		String[] ddArray = str.split(",");
		SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy-MM-dd");
		dd.setName(ddArray[0].replaceAll("r hq_str_" + code + "=\"", ""));
		dd.setSinaCode(code);
		try {
			dd.setHigh(Double.parseDouble(ddArray[3]));
			dd.setLow(Double.parseDouble(ddArray[4]));
			dd.setOpen(Double.parseDouble(ddArray[2]));
			dd.setClose(Double.parseDouble(ddArray[8]));
			dd.setVol(Integer.parseInt(ddArray[14]));
			dd.setDataDate(new Date());
		} catch (NumberFormatException e) {
		} catch (Exception e) {
		}
		return dd;
	}

	private static void readDatas(String code, String content) {
		String[] datas = content.split("\"d\"");
		List<KLine> dataList = new ArrayList<KLine>();
		String result = "";

		if (datas.length < 3) {
			System.out.println("无数据 ");
		}

		for (String s : datas) {

			KLine dd = new KLine();

			String[] ddArray = s.split(",");

			if (ddArray.length < 3) {
				continue;
			}

			SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			dd.setHigh(Double.parseDouble(ddArray[2].substring(5, ddArray[2].length() - 1)));
			dd.setLow(Double.parseDouble(ddArray[3].substring(5, ddArray[3].length() - 1)));
			dd.setClose(Double.parseDouble(ddArray[4].substring(5, ddArray[4].length() - 1)));
			dd.setVol(Integer.parseInt(ddArray[5].substring(5, ddArray[5].length() - 1)));
			// dd.setName(Dictionary.SinaDataDictionary.get(code).toString());
			dd.setSinaCode(code);

			result = result + ddArray[0].substring(2, ddArray[0].length() - 1) + "," + dd.getClose() + "," + dd.getLow()
					+ "," + dd.getHigh() + "," + (dd.getVol() * dd.getClose()) + "," + dd.getVol() + ",0," + "\r\n";

			dataList.add(dd);

		}
		try {
			JavaFile.writefile("d:/kline/" + code + ".txt", result, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;
	}

	private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "GBK"));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public static String getProducts(String node) {
		HttpClient httpclient = new DefaultHttpClient();

		HttpGet httpgets;

		List<String> rList = new ArrayList<String>();

		httpgets = new HttpGet(
				"http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getNameList?page=1&num=5&sort=position&asc=0&node="
						+ node);
		HttpResponse response;
		try {
			response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				String str = convertStreamToString(instreams);
				// System.out.println(str);
				httpgets.abort();
				return str;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	public static String getMain(String products) {

		products = products.replaceAll("\\{symbol:\"", "nf_").replaceAll("\"\\}", "").replaceAll("\\[", "")
				.replaceAll("\n", "").replaceAll("\\]", "");

		// System.out.println(products);

		HttpClient httpclient = new DefaultHttpClient();

		HttpGet httpgets;

		List<String> rList = new ArrayList<String>();

		httpgets = new HttpGet("http://hq.sinajs.cn/rn=3b774cc9&list=" + products);
		HttpResponse response;
		try {
			response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				String str = convertStreamToString(instreams);
				// System.out.println(str);

				String o[] = str.split("\n");

				double max = 0;
				String code = "";
				for (int i = 1; i < o.length; i++) {
					String vol = o[i].split(",")[6];

					if (Double.parseDouble(vol) > max) {
						max = Double.parseDouble(vol);
						code = o[i].split(",")[0].split("=")[0].split("_")[3];
					}

				}

				httpgets.abort();
				System.out.println(code);
				return code;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	public static String getMain1(String products) {

		products = products.replaceAll("\\{symbol:\"", "nf_").replaceAll("\"\\}", "").replaceAll("\\[", "")
				.replaceAll("\n", "").replaceAll("\\]", "");

		// System.out.println(products);

		HttpClient httpclient = new DefaultHttpClient();

		HttpGet httpgets;

		List<String> rList = new ArrayList<String>();

		httpgets = new HttpGet("http://hq.sinajs.cn/list=" + products);
		HttpResponse response;
		try {
			response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				String str = convertStreamToString(instreams);
				// System.out.println(str);

				String o[] = str.split("\n");

				double max = 0;
				String code = "";
				for (int i = 1; i < o.length; i++) {
					String vol = o[i].split(",")[13];

					if (Double.parseDouble(vol) > max) {
						max = Double.parseDouble(vol);
						code = o[i].split(",")[0].split("=")[0].split("_")[3];
					}

				}

				httpgets.abort();
				System.out.println(code);
				return code.toLowerCase();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	public static String getMain2(String products) {

		products = products.replaceAll("\\{symbol:\"", "nf_").replaceAll("\"\\}", "").replaceAll("\\[", "")
				.replaceAll("\n", "").replaceAll("\\]", "");

		// System.out.println(products);

		HttpClient httpclient = new DefaultHttpClient();

		HttpGet httpgets;

		List<String> rList = new ArrayList<String>();

		httpgets = new HttpGet("http://hq.sinajs.cn/rn=3b774cc9&list=" + products);
		HttpResponse response;
		try {
			response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				String str = convertStreamToString(instreams);
				// System.out.println(str);

				String o[] = str.split("\n");

				double max = 0;
				String code = "";
				for (int i = 1; i < o.length; i++) {
					String vol = o[i].split(",")[13];

					if (Double.parseDouble(vol) > max) {
						max = Double.parseDouble(vol);
						code = o[i].split(",")[0].split("=")[0].split("_")[3];
					}

				}

				httpgets.abort();
				System.out.println(code);
				return code.replaceAll("20", "0");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	public static List<String> getMainCode() {
		ArrayList<String> codeList = new ArrayList<String>();

//		String nodes[] = { "qz_qh", "gz_qh", "sngz_qh", "szgz_qh", "zzgz_qh", "engz_qh" };
//		for (String node : nodes) {
//			String plist = getProducts(node);
//			codeList.add(getMain(plist));
//		}
//, "jhb_qh", "jdm_qh" "wxd_qh",
		String nodes1[] = { "ry_qh"

//				, "yy_qh", "lv_qh", "xj_qh", "xing_qh", "tong_qh", "hj_qh", "lwg_qh", "xc_qh",
//				"qian_qh", "by_qh", "lq_qh", "rzjb_qh", "xi_qh", "ni_qh", "zj_qh", "ehj_qh", "bxg_qh", "pvc_qh",
//				"zly_qh", "de_qh", "dp_qh", "tks_qh", "jd_qh", "lldpe_qh", "jbx_qh", "xwb_qh", "dy_qh", "hym_qh",
//				"dd_qh", "jt_qh", "jm_qh", "ymdf_qh", "yec_qh", "gm_qh", "byx_qh" 

		};
		for (String node : nodes1) {
			String plist = getProducts(node);
			codeList.add(getMain1(plist));
		}

		String nodes2[] = { "pta_qh"

//				, "czy_qh", "ycz_qh", "czp_qh", "dlm_qh", "qm_qh", "bst_qh", "mh_qh", "zxd_qh",
//				"zc_qh", "bl_qh", "gt_qh", "mg_qh", "ms_qh", "xpg_qh", "hz_qh", "ns_qh", "cj_qh" 
//				

		};
		for (String node : nodes2) {
			String plist = getProducts(node);
			codeList.add(getMain2(plist));
		}
		return codeList;
	}

	public static void main(String[] args) throws InterruptedException, IOException {

		double firstTime = 0;
//				Date d = new Date();
//				int hours = d.getHours();
//
//				int minutes = d.getMinutes();
//				int seconds = d.getSeconds();
//
//				double now = (1 / 10e1) * hours + (1 / 10e3) * minutes + (1 / 10e5) * seconds; // 时间格式0.145100
////				System.out.println(now);
//				if (now >= 0.0930 && now <= 0.1130) {
//
//				} else if (now >= 0.13 && now <= 0.15) {
//
//				} else {
//					Thread.sleep(1);
//					continue;
//				}

		double b = 0;

//				List<String> conf = JavaFile.readfile("/home/etf.txt");
////				String[] conf = { "CON_SO_10001831#40", "CON_SO_10001832#150" };
//				for (String str : conf) {
//					String s = getData(str.split("#")[0]);
//					b = b + Double.parseDouble(s.split(",")[5]) * Integer.parseInt(str.split("#")[1]);
////					System.out.println(s.split(",")[0] + "    " + Double.parseDouble(s.split(",")[5]));
//				}

//		 get15mData("ta2501");
//
//		for (KLine k : s) {
//			System.out.print("" + k.getClose() + ",");
//
//		}
//		System.out.println();
//		for (KLine k : s) {
//
//			System.out.print("" + k.getVol() + ",");
//		}
//		List l = get15mData("c0");
//		while (true) {
//			//
//			// Calendar ca = Calendar.getInstance();
//			// int minute = ca.get(Calendar.MINUTE);// 分
//			// int hour = ca.get(Calendar.HOUR);// 小时
//			// if (hour == 10 && minute == 15) {
//			// Thread.sleep(1000 * 60 * 14);
//			// }
//			// if (hour == 11 && minute == 30) {
//			// Thread.sleep(1000 * 60 * 120);
//			// }
//			// if (hour == 15 && minute == 0) {
//			// Thread.sleep(1000 * 60 * 360);
//			// }
//			// if (hour == 23 && minute == 30) {
//			// Thread.sleep(1000 * 60 * 570);
//			// }
//			// getDatas();
//		}

		// Set<String> code = Dictionary.SinaDataDictionary.keySet();
		//
		// for (String c : code) {
		// // Turtle t = new Turtle(c, 50);
		// // Turtle t =null;
		// String returnStr;
		// returnStr = getData(c);
		//
		// List<DayData> dlist=readDatas(c,returnStr);
		//
		// Session session = HibernateUtil.getSessionFactory().openSession();
		// session.beginTransaction();
		// for(DayData d:dlist){
		// session.save(d);
		// }
		// session.getTransaction().commit();
		//
		// }
		//
		// String s1[]={
		// // "TA",
		// // "OI",
		// // "RM",
		// // "ZC",
		// // "WH",
		// // "SR",
		// // "CF",
		// // "MA",
		// // "FG"
		// // ,
		// "v",
		// "p",
		// "m",
		// "i",
		// "jd",
		// "l",
		// "pp",
		// "y",
		// "c",
		// "a",
		// "j",
		// "jm",
		// "cs",
		// "al",
		// "ru",
		// "zn",
		// "cu",
		// "au",
		// "rb",
		// "pb",
		// "ag",
		// "bu",
		// "sn",
		// "ni"
		// //,
		// };
		// Session session = HibernateUtil.getSessionFactory().openSession();
		// session.beginTransaction();
		// for(String ss:s1){
		// String content=getData(ss+"1701");
		// String[] datas = content.split("],\\[");
		// for (String s : datas) {
		// try {
		// DayData dd = new DayData();
		// String[] ddArray = s.split(",");
		// SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy-MM-dd");
		// dd.setHigh(Double.parseDouble(ddArray[2].substring(1,
		// ddArray[2].length() - 1)));
		// dd.setLow(Double.parseDouble(ddArray[3].substring(1,
		// ddArray[3].length() - 1)));
		// dd.setOpen(Double.parseDouble(ddArray[1].substring(1,
		// ddArray[1].length() - 1)));
		// dd.setClose(Double.parseDouble(ddArray[4].substring(1,
		// ddArray[4].length() - 1)));
		// dd.setVol(Integer.parseInt(ddArray[5].substring(1,
		// ddArray[5].length() - 1)));
		// dd.setDataDate(myFmt1.parse(ddArray[0].substring(1,
		// ddArray[0].length() - 1)));
		// dd.setName(ss+"1701");
		// session.save(dd);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		//
		// }
		//
		// session.getTransaction().commit();

		// HibernateUtil.selectDatas("NI0", 1);
	}
}